//创建资源类
class ShareDate{
    //定义共享资源
    private Integer number = 0;

    //1.创建资源类方法
    public synchronized void incre() throws InterruptedException {
        //2.判断
        while (number!=0) {
            this.wait();
        }
        number++;  //3.干活
        System.out.println(Thread.currentThread().getName() + ": " + number);
       // this.notify();  //随机唤醒一个线程


        //4.通知
        this.notifyAll(); //唤醒其他所有线程
    }

    public synchronized void decre() throws InterruptedException {
        while (number!=1){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + ": " + number);
        this.notifyAll();
    }



}

public class ThreadCommunicate {


    /**
     *  1.创建资源类以及线程安全方法
     *  2.判断，干活，通知
     */
       public static void main(String[] args) {
        ShareDate shareDate = new ShareDate();



        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDate.decre();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"aaa").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDate.incre();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"bbb").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDate.decre();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"ccc").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDate.incre();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"ddd").start();
    }

}